#!/bin/bash

CODE=""
OUTPUT=""
INSTALLER=""
NOT_EXIST=0

show_help() {
cat << EOF
Usage: ${0##*/} [Language Code] [Output File]
Dump the dicionary to specific file for the nvim-cmp

    LanguageCode        Aspell Compatible Language Code
    Output File         The file to store dictionary
EOF
}

guess_system() {
  local shellopts=$(shopt -p extglob)
  shopt -u extglob
  if ! source "/etc/os-release"; then
    echo "This script is only compatible with Linux distribution!"
    exit 1
  fi
  eval "$shellopts"

  case "$NAME" in
    "Arch Linux")
      echo "Using pacman"
      PACKAGER="sudo pacman -S --needed"
      ;;
    "Ubuntu")
      echo "Using apt"
      PACKAGER="sudo apt install"
      ;;
    *)
      echo "Unsupported distribution, please open a new issue for support"
      exit 1
    ;;
  esac
}

check_aspell() {
  if ! which aspell > /dev/null 2>&1; then
    NOT_EXIST=1
  fi
}

install_aspell() {
  if (( $NOT_EXIST > 0 )); then
    $PACKAGER "aspell aspell-$CODE"
  fi
}

if [[ "$@" == "" ]]; then
  show_help
  exit 1
fi

CODE="$1"
shift
OUTPUT="$1"

if [[ "$CODE" == "" ]]; then
  echo "Language code is required"
  show_help
  exit 1
fi

if [[ $OUTPUT == "" ]]; then
  OUTPUT="$CODE.dict"
fi

guess_system
check_aspell
install_aspell

aspell -d $CODE dump master | aspell -l $CODE expand > $OUTPUT
